package cn.itcast.nems.studentrecord.scheduler;

import cn.itcast.nems.common.account.AccountHolder;
import cn.itcast.nems.common.tenant.TenantInfoHolder;
import cn.itcast.nems.studentrecord.dto.studentrecord.StudentRecordMessageDTO;
import cn.itcast.nems.studentrecord.service.studentrecord.StudentRecordMessageService;
import cn.itcast.nems.studentrecord.service.studentrecord.StudentRecordService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 根据学籍出班日期，发送出班消息
 * author liyong
 * create: 2023-12-04 09:47:57
 **/
@AllArgsConstructor
@Component
public class OutClazzMessageJob {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final StudentRecordMessageService studentRecordMessageService;
    private final StudentRecordService studentRecordService;


    @XxlJob("sendOutClazzMessages")
    public ReturnT<String> sendOutClazzMessages(String param) {
        long s = System.currentTimeMillis();
        logger.warn("Out clazz message job start with params {}...", param);
        LocalDate outDate;
        if (StringUtils.hasText(param)) {
            outDate = LocalDate.parse(param.trim(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } else {
            outDate = LocalDate.now();
        }
        AccountHolder.setSchedulerAccountInfo();
        TenantInfoHolder.setDefaultTenantInfo();
        final List<StudentRecordMessageDTO> outStudentRecords = this.studentRecordService.findOutStudentRecords(outDate);
        outStudentRecords.forEach(studentRecordMessageService::studentRecordOut);
        String msg = String.format("%d个学籍出班", outStudentRecords.size());
        long end = System.currentTimeMillis();
        logger.warn("{} 消耗 {}'ms", msg, (end - s));
        return new ReturnT<>(msg);
    }
}
